package com.hxzy.security.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSONObject;
import com.hxzy.common.TZXMConst;
import com.hxzy.common.util.ServletUtil;
import com.hxzy.common.vo.CodeEnum;
import com.hxzy.common.vo.R;
import com.hxzy.vo.system.HxzyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 用户注销重写拦截器
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private RedisTemplate  redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String jwtToken = request.getHeader("Authorization");
        if (jwtToken.startsWith("Bearer ")) {
            jwtToken = jwtToken.replace("Bearer ", "");
        }
        //5、令牌有效的，从数据库中 查询出这个令牌uuid对应的employee的信息 存储来（放哪里?）
        JWT jwt = JWTUtil.parseToken(jwtToken);
        String uuid = jwt.getPayload(TZXMConst.LOGIN_USER_KEY).toString();
        //去redis中查询
        String redisKey = TZXMConst.LOGIN_TOKEN_KEY + uuid;

        //移出redis中的值
        this.redisTemplate.delete(redisKey);

        ServletUtil.outJson(response,CodeEnum.SUCCESS);
    }
}
